/**
 * Created by zhouli on 18/3/13
 * Email li.zhou@huilianyi.com
 */
import React from 'react';
import {connect} from 'react-redux';
import {
  Table, Button, Badge, message, Icon, Input, Menu,
  Dropdown, Modal, Upload, Popover
} from 'antd';
import CCService from 'containers/setting/cost-center/cost-center.service';
import menuRoute from 'routes/menuRoute';
import 'styles/setting/cost-center/cost-center-detail.scss';
import {SelectDepOrPerson} from 'components/index';
import {deepCopy, messages} from "share/common";
import ExportModal from 'components/template/export-modal/export-modal';
import ResizeTable from "components/resize-table";
import {superThrottle, getSubText} from 'share/common';

class CostCenterAssignment extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      dataAll: false,//是否全选的标志
      reverseSelectionMap: {},//当全选的时候，记住这些没勾选的,每一页一个key
      editing: false,
      //成本中心项列表
      data: [],
      pagination: {
        total: 0,
        page: 0,
        pageSize: 10,
      },
      //被选择了的成本中心项
      selectedRowKeys: [],
      costCenterItemName: "",//输入搜索成本中心项名称与code
      costCenterExtendFiled: menuRoute.getRouteItem('cost-center-extend-filed', 'key'),//成本中心扩展字段
      columns: [
        {
          title: messages('basic-5.key565')/*成本中心项名称*/,
          dataIndex: "name",
          width: '15%',
          render: text => <span>{text ? <Popover placement="topLeft" content={text}>{text}</Popover> : '-'}</span>
        },
        {
          title: messages('basic-5.key566')/*父级成本中心项*/,
          dataIndex: "parentCostCenterItemName",
          width: '15%',
          render: text => <span>{text ? <Popover placement="topLeft" content={text}>{text}</Popover> : '-'}</span>
        },
        {
          title: messages('basic-5.key508')/*编码*/,
          dataIndex: "code",
          width: '15%',
          render: text => <span>{text ? <Popover placement="topLeft" content={text}>{text}</Popover> : '-'}</span>
        },
        {
          title: messages('common.sequence')/*序号*/,
          dataIndex: "sequenceNumber",
          width: '10%'
        },
        {
          title: messages('basic-5.key567')/*经理*/,
          dataIndex: "managerFullName",
          width: '15%',
          render: text => <span>{text ? <Popover placement="topLeft" content={text}>{text}</Popover> : '-'}</span>
        },
        {
          title: messages('basic-5.key610')/*全员可见性*/,
          dataIndex: "public",
          render: enabled => (
            <Badge status={enabled ? 'success' : 'error'}
                   text={enabled ? messages('basic-5.key20')/*启用temp*/ : messages('basic-5.key21')/*禁用temp*/}/>)
        },
        {
          title: messages('common.column.status')/*状态*/,
          dataIndex: 'enabled',
          render: enabled => (
            <Badge status={enabled ? 'success' : 'error'}
                   text={enabled ? messages('basic-5.key20')/*启用temp*/ : messages('basic-5.key21')/*禁用temp*/}/>)
        },
      ],
      infoData: {},
      downloading: false,
      addLoading: false,
      enableLoading: false,
    };
  }

  componentDidMount() {
    this.getList();
  }

  //得到列表数据
  //isClearRowSelection boolean是否清空选中的
  getList(isClearRowSelection) {
    this.setState({loading: true});
    const {pagination, costCenterItemName} = this.state;
    CCService.getCostCenterItemsAssignment(pagination.page, costCenterItemName)
      .then((response) => {
        if (isClearRowSelection) {
          this.clearRowSelection()
        }
        let oids = [];
        response.data.map((item) => {
          item.key = item.id;
          oids.push(item.costCenterItemOID);
        });
        pagination.total = Number(response.headers['x-total-count']);
        pagination.current = pagination.page + 1;
        this.setState({
          data: response.data,
          loading: false,
          pagination
        }, () => {
          if (this.state.dataAll) {
            //如果有全选全部,翻页就立即勾选,并且需要排除掉没有勾选的
            let reverseSelectionMap = this.state.reverseSelectionMap;
            let currentPageUnselected = reverseSelectionMap[this.state.pagination.page];
            let currentPageSelected = CCService.getSelected(oids, currentPageUnselected);
            this.onSelectChange(currentPageSelected);
          }
        })
      }).catch(error => {
      this.setState({
        data: [{name: 1}],
        loading: false,
      })
      });
  }

  //分页点击
  onChangePager = (pagination, filters, sorter) => {
    this.setState({
      pagination: {
        page: pagination.current - 1,
        pageSize: pagination.pageSize
      }
    }, () => {
      this.getList();
    })
  };

  //成本中心项详情
  handleRowClick = (record) => {
    let CostCenterItemDetail = menuRoute.getRouteItem('cost-center-assignment-detail');
    let path = CostCenterItemDetail.url
      .replace(":id", record.costCenterOID)
      .replace(":costId", record.costCenterItemOID);
    this.context.router.push(path);
  };

  //批量关联人员到成本中心项
  batchAddPerson = (arr) => {
    if (arr.length < 1) {
      message.warn(messages('basic-5.key510')/*请选择人员*/);
      return;
    }
    let userOIDs = [];
    arr.map((item) => {
      userOIDs.push(item.userOID)
    });
    let params = null;
    if (this.state.dataAll) {
      let costCenterItemOIDs = CCService.getReverseSelection(deepCopy(this.state.reverseSelectionMap));
      params = {
        userOIDs: userOIDs,
        costCenterItemOIDs,
        selectMode: "all_page",
      }
    } else {
      if (this.state.selectedRowKeys.length < 1) {
        message.warn(messages('basic-5.key574')/*请选择成本中心项*/);
        return;
      }
      params = {
        userOIDs: userOIDs,
        costCenterItemOIDs: this.state.selectedRowKeys,
        selectMode: "default",
      }
    }
    this.setState({
      addLoading: true,
    });
    CCService.batchAddEmployee(params)
      .then((res) => {
        this.setState({
          addLoading: false,
        });
        message.success(messages('common.operate.success')/*操作成功*/);
      }).catch(err => {
      this.setState({
        addLoading: false,
      });
    })
  };

  //选中项发生变化的时的回调
  onSelectChange = (selectedRowKeys) => {
    this.setState({selectedRowKeys: selectedRowKeys});
    if (this.state.dataAll) {
      //如果有全选标志，需要记住没选的
      let reverseSelectionMap = this.state.reverseSelectionMap;
      let allKeys = this.state.data.map(item => {
        return item.costCenterItemOID;
      });
      let unSelectedData = CCService.getUnSelected(deepCopy(allKeys), deepCopy(selectedRowKeys));
      reverseSelectionMap[this.state.pagination.page] = unSelectedData;

      this.setState({
        reverseSelectionMap,
      })
    } else {
      //不需要记住
      this.setState({
        reverseSelectionMap: {}
      })
    }
  };

  //批量启用禁用
  //type enabled启用 disabled禁用
  handleBatch = (type) => {
    let enable = false;
    if (type === 'enabled') {
      enable = true;
    }
    let data = null;
    if (this.state.dataAll) {
      //反选模式
      data = {
        costCenterItemOIDs: CCService.getReverseSelection(deepCopy(this.state.reverseSelectionMap)),
        enable: enable,
        selectMode: "all_page",
      }
    } else {
      if (this.state.selectedRowKeys.length < 1) {
        //请选择成本中心项
        message.warn(messages('basic-5.key574')/*请选择成本中心项*/);
        return;
      }
      //正常模式
      data = {
        costCenterItemOIDs: this.state.selectedRowKeys,
        enable: enable,
        selectMode: "default",
      }
    }
    this.setState({
      enableLoading: true,
    });
    CCService.batchEnableOrDisable(data)
      .then(res => {
        this.setState({
          enableLoading: false,
        });
        message.success(messages('common.operate.success')/*操作成功*/);
        this.getList(true);
      }).catch(err => {
      this.setState({
        enableLoading: false,
      });
    })
  };

  //清空选择框：选了的成本中心项
  clearRowSelection() {
    this.setState({
      selectedRowKeys: []
    });
  }

  //搜索成本中心项
  emitEmptyForDep = () => {
    this.userNameInput.focus();
    this.setState({costCenterItemName: ''}, () => {
      this.onChangeCostCenterItemName();
    });
  };
  //节流函数
  onChangeSetUserDepName = superThrottle(() => {
    this.onChangeCostCenterItemName();
  }, 500, 3000);
  //为了节流函数
  onInputUserDepName = (e) => {
    this.setState({costCenterItemName: getSubText(e.target.value,100)});
  };
  //搜索成本中心项
  onChangeCostCenterItemName = (e) => {
    const {pagination} = this.state;
    pagination.page = 0;
    this.setState({
      loading: true,
      pagination
    }, () => {
      this.getList(true);
    });
  };
  cancelAll = (selectedRowKeys) => {
    this.setState({
      dataAll: false,
      selectedRowKeys: []
    })
  };

  dataAll = (selectedRowKeys) => {
    this.setState({
      dataAll: true,
      reverseSelectionMap: {},//点击一次全选全部就返回
      selectedRowKeys: [...selectedRowKeys]
    })
  };

  pageAll = (selectedRowKeys) => {
    this.onSelectChange(selectedRowKeys);
    this.setState({
      selectedRowKeys: [...selectedRowKeys]
    })
  };

  render() {
    const {columns, data, loading, pagination, infoData, editing, selectedRowKeys, enableLoading, addLoading,
      costCenterItemName,} = this.state;
    let rowSelection = {
      selectedRowKeys,
      hideDefaultSelections: true,//去掉默认的
      onChange: this.onSelectChange,
      onSelection: this.onSelection,
      selections: [
        {
          key: 'data-all',
          text: messages('basic-5.key576')/*全选全部*/,
          onSelect: this.dataAll
        },
        {
          key: 'page-all',
          text: messages('basic-5.key577')/*全选当页*/,
          onSelect: this.pageAll
        },
        {
          key: 'cancel-all',
          text: messages('common.cancel')/*取消*/,//取消
          onSelect: this.cancelAll
        },
      ]
    };
    const suffix = costCenterItemName ? <Icon type="close-circle" onClick={this.emitEmptyForDep}/> : null;
    const menuExport = (
      <Menu>
        <Menu.Item key={3}>
          <ExportModal
            codeCheck={true}
            exportTitle={messages('basic-5.key578')/*导出成本中心项*/}
            exportType="cost_center_item_by_manager"
            exportCondition={{
              costCenterId: infoData.id
            }}
            exportCommand={"cost_center_item_by_manager"}
          />
        </Menu.Item>
        <Menu.Item key={4}>
          <ExportModal
            codeCheck={true}
            exportTitle={messages('basic-5.key579')/*导出成本中心项-人员*/}
            exportType="cost_center_item_by_manager"
            exportCondition={{
              setOfBooksId: infoData.setOfBooksId
            }}
            exportCommand={"cost_center_item_with_user_by_manager"}
          />
        </Menu.Item>
      </Menu>
    );
    return (
      <div className="cost-center-detail full-height-page">
        <div className="table-header">
          <div className="table-header-title-cost">
            {messages('common.total',{arg1: pagination.total})/*共搜索到 {arg1} 条数据*/}
          </div>
          <div className="table-header-buttons">
            <div className="left">
              <div className="left-edge-gap">
                <Dropdown overlay={menuExport} placement="bottomCenter">
                  <Button>{messages('basic-5.key559')/*导出数据*/}<Icon type="down"/></Button>
                </Dropdown>
              </div>
              <div className="">
                <SelectDepOrPerson
                  costCenterAssign={window.location.href.indexOf("cost-center-assignment") !== -1}
                  buttonLoading={addLoading}
                  buttonDisabled={!selectedRowKeys.length}
                  title={messages('basic-5.key514')/*批量添加员工*/}
                  onlyPerson={true}
                  onConfirm={this.batchAddPerson}/>
              </div>

              <Button onClick={() => this.handleBatch('enabled')} disabled={!selectedRowKeys.length} loading={enableLoading}>
                {messages('basic-5.key587')/*批量启用*/}
              </Button>
              <Button onClick={() => this.handleBatch('disabled')} disabled={!selectedRowKeys.length} loading={enableLoading}>
                {messages('basic-5.key588')/*批量禁用*/}
              </Button>
            </div>

            <div className="right table-header-inp right-edge-gap">
              <Input
                className='cost-center-item-name-search'
                key={'costCenterItemName-search'}
                placeholder={messages('basic-5.key593')/*输入成本中心项名称或编码*/}
                prefix={<Icon type="search" style={{color: 'rgba(0,0,0,.25)'}}/>}
                suffix={suffix}
                value={costCenterItemName}
                onInput={this.onInputUserDepName}
                onChange={this.onChangeSetUserDepName}
                ref={node => this.userNameInput = node}/>
            </div>
          </div>
          <ResizeTable
            columns={columns}
            dataSource={data}
            pagination={pagination}
            loading={loading}
            rowKey="costCenterItemOID"
            bordered
            onChange={this.onChangePager}
            rowSelection={rowSelection}
            size="middle"
            onRow={record => ({onClick: () => this.handleRowClick(record)})}
          />
        </div>
      </div>
    )
  }
}

CostCenterAssignment.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    user: state.login.user,
    company: state.login.company,
    tenantMode: state.main.tenantMode,
  }
}

export default connect(mapStateToProps)(CostCenterAssignment);
